<template>
  <div class="data-backup">
    <div class="app-container">
      <div class="mainbox">
        <Header :header-name="$route.meta.title" />

        <div class="data-backup-body">

          <el-form ref="form" :model="form" :rules="rules" label-width="140px">
            <el-form-item label-width="0">
              <el-button v-permission="['DATABACKUP_SAVE']" type="primary" :loading="!canSave" :disabled="!canSave" @click="saveBtn"> 保存 </el-button>
              <el-button v-permission="['DATABACKUP_BACKUP']" :loading="!canSave" :disabled="!canSave" @click="runBtn"> 立即备份 </el-button>
            </el-form-item>

            <el-divider />
            <p class="title"> 设置备份参数 </p>

            <el-form-item label="备份文件保存路径:" prop="fileSavePath">
              <el-input v-model="form.fileSavePath" :maxlength="50" clearable placeholder="请输入备份文件保存路径" />
              注：请填写绝对路径
            </el-form-item>
            <el-form-item label="保存备份数量:" prop="autoSaveMaxSize">
              <el-input-number v-model="form.autoSaveMaxSize" :controls="false" :max="100" :min="0" />
              注：备份数量超出限制时，会删除旧的备份数据
            </el-form-item>

            <el-divider />

            <p class="title">
              设置自动备份
              <el-switch
                v-model="form.autoSaveFlag"
                active-text="开"
                active-value="Y"
                inactive-text="关"
                inactive-value="N"
              />
            </p>

            <div v-if="form.autoSaveFlag === 'Y'">
              <el-form-item label="备份周期:" prop="autoSaveCron">
                <el-input v-model="form.autoSaveCron" style="width: 400px;" disabled clearable :maxlength="100" placeholder="请输入CRON表达式">
                  <el-button slot="append" @click="$refs.vcrontabRef.showDialog()"> 生成表达式 </el-button>
                </el-input>
              </el-form-item>
            </div>

            <el-divider />
          </el-form>

          <p class="title"> 备份记录

            <el-button class="refresh-button" size="small" :loading="loading" :disabled="loading" @click="getPage"> 刷新 </el-button>
          </p>

          <FlexTable
            v-loading="loading"
            border
            :data="tableData"
            :columns="columnsOptions"
          />

          <el-pagination
            :page-size="pagination.pageSize"
            :current-page.sync="pagination.pageNo"
            layout="prev, pager, next, jumper"
            :total="pagination.totalPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 生成CRON表达式 -->
    <dt-Vcrontab ref="vcrontabRef" v-model.trim="form.autoSaveCron" />
  </div>
</template>

<script>
import { detailApi, saveApi, pageApi, runApi, deleteApi } from '@/api/monitorManage/dataBackup'
export default {
  name: 'DataBackup',

  data () {
    return {
      loading: false,
      canSave: true,
      form: {
        autoSaveFlag: '',
        autoSaveMaxSize: '',
        fileSavePath: '',
        autoSaveCron: ''
      },
      rules: {
        fileSavePath: [{ required: true, message: '请输入备份文件保存路径', trigger: 'blur' }],
        autoSaveCron: [{ required: true, message: '请选择备份周期', trigger: 'change' }],
        autoSaveMaxSize: [{ required: true, message: '请输入保存备份数量:', trigger: 'blur' }]
      },
      tableData: [],
      columnsOptions: [
        { label: '备份项目', prop: 'fileName' },
        { label: '数据大小', prop: 'dataSizeInfo' },
        { label: '备份时间', prop: 'backupTime' },
        { label: '备份人', prop: 'createUserName' },
        { label: '类型', prop: 'backupType',
          customRender: scope => {
            return scope.row.backupType === 1 ? '自动备份' : '手动备份'
          }
        },
        { label: '备份状态', prop: 'result',
          customRender: scope => {
            const resultList = ['成功', '失败', '执行中', '等待中']
            return resultList[scope.row.result]
          }
        },
        { label: '操作', prop: 'systemName', width: 120,
          customRender: (scope) => {
            return [
              <el-button vPermission={['DATABACKUP_DEL']} type='text' class='text-del-btn' onClick={() => this.delBtn(scope.row)}> 删除 </el-button>
            ]
          }
        }
      ],
      // 分页相关
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalPage: 0
      },
      formBackup: ''
    }
  },

  created () {
    this.getDetail()
    this.getPage()
  },

  methods: {
    // 获取备份配置详情
    getDetail () {
      detailApi()
        .then(({ code, data }) => {
          if (code === '00000') {
            const { id, ...other } = data
            this.form = other
            this.formBackup = JSON.stringify(other)
          }
        })
    },

    // 保存按钮
    saveBtn () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.canSave = false
          saveApi(this.form)
            .then(({ code }) => {
              if (code === '00000') {
                this.$message.success('保存成功')
                this.formBackup = JSON.stringify(this.form)
              }
            }).finally(() => {
              this.canSave = true
            })
        }
      })
    },

    // 立即备份按钮
    runBtn () {
      if (this.formBackup !== JSON.stringify(this.form)) {
        return this.$message.warning('您的备份数据发生变化，请先保存！')
      }

      this.canSave = false
      runApi()
        .then(({ code, message }) => {
          if (code === '00000') {
            this.$message.success(message)
            this.getPage()
          }
        }).finally(() => {
          this.canSave = true
        })
    },

    // 备份记录
    getPage () {
      this.loading = true
      pageApi({
        pageSize: this.pagination.pageSize,
        pageNo: this.pagination.pageNo
      })
        .then(({ code, data }) => {
          if (code === '00000') {
            this.tableData = data.rows
            this.pagination.totalPage = data.totalRows
          }
        }).finally(() => {
          this.loading = false
        })
    },

    // 删除场景分类按钮
    delBtn (data) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteApi({
          id: data.id
        }).then(({ code }) => {
          if (code === '00000') {
            this.$message.success('删除成功')
            this.getPage()
          }
        })
      })
    },

    // 分页操作
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.getPage()
    },
    handleCurrentChange (val) {
      this.pagination.pageNo = val
      this.getPage()
    }
  }
}
</script>

<style lang="scss" scoped>
  .data-backup {
    background: #F2F2F2;

    &-body {
      background: #fff;
      margin-top: 10px;
      padding: 20px;
      height: calc(100vh - 254px);
      overflow-y: auto;

      .el-input {
        width: 200px;
      }

      ::v-deep .el-input-number {
        width: 80px;
        .el-input .el-input__inner {
          text-align: left;
        }
      }

      .title {
        color: #1296DB;
      }
      .el-switch {
        margin-left: 20px;
        margin-top: -2px;
      }
      .refresh-button {
        margin-left: 20px;
      }
    }
    .el-pagination {
      text-align: right;
      margin-top: 20px;
    }
  }
</style>
